package DatabaseManaging;
//package Autodesk;
//
//import java.io.BufferedInputStream;
//import java.io.BufferedReader;
//import java.io.File;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.net.URL;
//import java.net.URLConnection;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.StringTokenizer;
//
//import com.amazonaws.auth.BasicAWSCredentials;
//import com.amazonaws.auth.AWSCredentials;
//import com.amazonaws.services.s3.AmazonS3;
//import com.amazonaws.services.s3.AmazonS3Client;
//import com.amazonaws.services.s3.model.AbortMultipartUploadRequest;
//import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest;
//import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest;
//import com.amazonaws.services.s3.model.InitiateMultipartUploadResult;
//import com.amazonaws.services.s3.model.PutObjectRequest;
//import com.amazonaws.services.s3.model.PartETag;
//import com.amazonaws.services.s3.model.UploadPartRequest;
//
//public class DataUploader {
//
//	private final static String accessKey = "AKIAJVRTQPCE73KSXEXA";
//	private final static String secretKey = "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";
//	private static final int CHUNK_SIZE = 5 * 1024 * 1024;
//	private static final int MAX_RETRY = 3;
//	
//
//    /**
//     * Creates a temporary file with text data to demonstrate uploading a file
//     * to Amazon S3
//     *
//     * @return A newly created temporary file with text data.
//     *
//     * @throws IOException
//     */
//    private static File downloadFile(String url) throws IOException {
//        //File file = File.createTempFile("aws-java-sdk-", ".txt");
//    	File file=null;
//    	String filename = null;
//
//        
//        URL u = new URL(url);
//        URLConnection uc = u.openConnection();
//        String contentType = uc.getContentType();
//        int contentLength = uc.getContentLength();
//        if (contentType.startsWith("text/") || contentLength == -1) { // write code for text file
//          throw new IOException("This is not a binary file.");
//	    } else {
//	        InputStream raw = uc.getInputStream();
//	        InputStream in = new BufferedInputStream(raw);
//	        byte[] data = new byte[contentLength];
//	        int bytesRead = 0;
//	        int offset = 0;
//	        while (offset < contentLength) {
//	          bytesRead = in.read(data, offset, data.length - offset);
//	          if (bytesRead == -1)
//	            break;
//	          offset += bytesRead;
//	        }
//	        in.close();
//	
//	        if (offset != contentLength) {
//	          throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
//	        }
//	
//	        filename = u.getFile();
//	        filename = filename.substring(filename.lastIndexOf('/') + 1);
//	        FileOutputStream out = new FileOutputStream(filename);
//	        out.write(data);
//	        out.flush();
//	        out.close();
//        }
//        file = new File(filename);
//
//        return file;
//    }
//
//    /**
//     * Displays the contents of the specified input stream as text.
//     *
//     * @param input
//     *            The input stream to display as text.
//     *
//     * @throws IOException
//     */
//    private static void displayTextInputStream(InputStream input) throws IOException {
//        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
//        while (true) {
//            String line = reader.readLine();
//            if (line == null) break;
//
//            System.out.println("    " + line);
//        }
//        System.out.println();
//    }
//    
//    protected static void uploadFiles(String files, String s3bucket, String uploadtoBucketFolder) throws IOException {
//    	
//    	StringTokenizer tokenizer = new StringTokenizer(files, ",");
//		while (tokenizer.hasMoreTokens()) {
//			String token = tokenizer.nextToken();
//			File f = downloadFile(token);
//			System.out.println("Uploading a new object to S3 from a file\n");
//			
//	        AmazonS3 s3 = new AmazonS3Client(new BasicAWSCredentials(DataUploader.accessKey, DataUploader.secretKey));
//	        String fname = f.getName().substring(f.getName().lastIndexOf("/")+1);
//	        fname = fname.substring(fname.indexOf("-") +1);
//	        fname = fname.replace("-", "/");
//	        s3.putObject(new PutObjectRequest(s3bucket, uploadtoBucketFolder.concat(fname), f));
//			
//		}
//    	
//    }
//
//    protected static void uploadFilesMultipart(String filePath, String bucketName, String keyName) throws Exception {
//    	
//    	StringTokenizer tokenizer = new StringTokenizer(filePath, ",");
//		while (tokenizer.hasMoreTokens()) {
//			String token = tokenizer.nextToken();
//			File f = downloadFile(token);
//			System.out.println("Uploading a new object to S3 from a file using multipart upload\n");
//			
//	        AmazonS3 s3Client = new AmazonS3Client(new BasicAWSCredentials(DataUploader.accessKey, DataUploader.secretKey));
//	        String fname = f.getName().substring(f.getName().lastIndexOf("/")+1);
//	        fname = fname.substring(fname.indexOf("-") +1);
//	        fname = fname.replaceFirst("-", "/");
//	        //String fpath = fname.substring(0,fname.lastIndexOf("/"));
//	        //fname = fname.substring(fname.lastIndexOf("/") +1);
//	        //fname.replace("-", "/").substring(fname.indexOf("/") +1);
//	        fname = "bee/data/store/input/" + fname;
//	        //s3.putObject(new PutObjectRequest("spwsa", fname, f));
//	        
//	        // Create a list of UploadPartResponse objects. You get one of these
//	        // for each part upload.
//	        List<PartETag> partETags = new ArrayList<PartETag>();
//
//	        // make sure that the bucket exists
//	        //createBucketIfNotExists(bucketName, accessKey, secretKey);
//
//	        // delete the file from bucket if it already exists there
//	        //s3Client.deleteObject(bucketName, keyName);
//
//	        // Initialize.
//	        InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucketName, keyName);
//	        InitiateMultipartUploadResult initResponse = s3Client.initiateMultipartUpload(initRequest);
//
//	        File file = new File(filePath);
//
//	        long contentLength = file.length();
//	        long partSize = CHUNK_SIZE; // Set part size to 5 MB.
//	        int numOfParts = 1;
//	        if (contentLength > CHUNK_SIZE) {
//	            if (contentLength % CHUNK_SIZE != 0) {
//	                numOfParts = (int)((contentLength/partSize)+1.0);
//	            }
//	            else {
//	                numOfParts = (int)((contentLength/partSize));
//	            }
//	        }
//
//	        try {
//	            // Step 2: Upload parts.
//	            long filePosition = 0;
//	            for (int i = 1; filePosition < contentLength; i++) {
//	                // Last part can be less than 5 MB. Adjust part size.
//	                partSize = Math.min(partSize, (contentLength - filePosition));
//
//	                System.out.println("Start uploading part[" + i + "] of [" + numOfParts + "]");
//
//	                // Create request to upload a part.
//	                UploadPartRequest uploadRequest = new UploadPartRequest()
//	                .withBucketName(bucketName).withKey(keyName)
//	                .withUploadId(initResponse.getUploadId()).withPartNumber(i)
//	                .withFileOffset(filePosition)
//	                .withFile(file)
//	                .withPartSize(partSize);
//
//	                // repeat the upload until it succeeds or reaches the retry limit
//	                boolean anotherPass;
//	                int retryCount = 0;
//	                do {
//	                    anotherPass = false;  // assume everything is ok
//	                    try {
//	                    	System.out.println("Uploading part[" + i + "]");
//	                        // Upload part and add response to our list.
//	                        partETags.add(s3Client.uploadPart(uploadRequest).getPartETag());
//	                        System.out.println("Finished uploading part[" + i + "] of [" + numOfParts + "]");
//	                    } catch (Exception e) {
//	                    	System.out.println("Failed uploading part[" + i + "] due to exception. Will retry... Exception: " + e.getMessage());
//	                        anotherPass = true; // repeat
//	                        retryCount++;
//	                    }
//	                }
//	                while (anotherPass && retryCount < MAX_RETRY);
//
//	                filePosition += partSize;
//	                System.out.println("filePosition=[" + filePosition + "]");
//
//	            }
//	            System.out.println("Finished uploading file");
//
//	            // Complete.
//	            CompleteMultipartUploadRequest compRequest = new 
//	            CompleteMultipartUploadRequest(
//	                    bucketName, 
//	                    keyName, 
//	                    initResponse.getUploadId(), 
//	                    partETags);
//
//	            s3Client.completeMultipartUpload(compRequest);
//
//	            System.out.println("multipart upload completed.upload id=[" + initResponse.getUploadId() + "]");
//	        } catch (Exception e) {
//	            s3Client.abortMultipartUpload(new AbortMultipartUploadRequest(
//	                    bucketName, keyName, initResponse.getUploadId()));
//
//	            System.out.println("Failed to upload due to Exception:" + e.getMessage());
//
//	            throw e;
//	        }
//			
//		}
//    	
//    }
//
//}